﻿
using MobileControlGuru.Base;
using MobileControlGuru.sqlite_db;
using MobileControlGuru.Src;
using MobileControlGuru.Tools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MobileControlGuru.AutoTask
{

    public class TaskJson
    {


        public class OpType
        {
            public string Name { set; get; }
            public string Oprate { set; get; }
            public bool IsAdb { set; get; }

            public override string ToString()
            {
                return Name;
            }

            public OpType(string name, string oprate, bool isAdb = true)
            {
                Name = name;
                Oprate = oprate;
                IsAdb = isAdb;
            }
        }

        public static List<OpType> OpTypes = new List<OpType>() {
           new OpType("点击","shell input tap"),
           new OpType("滑动","shell input swipe"),
           new OpType("按键","shell input keyevent"),
           new OpType("输入文本","shell input text"),
           new OpType("输入汉字","shell am broadcast -a ADB_INPUT_TEXT --es msg"),
           new OpType("设置剪贴板","shell am broadcast -a clipper.set -e text"),
           new OpType("获取剪贴板","shell am broadcast -a clipper.get"),
           new OpType("模拟长按操作","shell input swipe"),
           new OpType("启动APP","shell am start -n"),
           new OpType("睡眠","shell sleep "),
           new OpType("强制关闭应用","shell am force-stop "),
           new OpType("强制安装apk包"," install -r "),
           new OpType("卸载包","  uninstall  "),
           new OpType("自定义命令","custom",false),
           new OpType("uiautomator dump","shell uiautomator dump"),
           new OpType("pull uiautomator dump","pull /sdcard/window_dump.xml "),
           new OpType("截屏并获取","shell screencap"),
            new OpType("复制到"," push "),
           //new OpType("截屏"," shell screencap -p /sdcard/"+DateTime.Now.ToString("yyyyMMddHHmmss")+".png"),
           //new OpType("拉取文件"," shell screencap -p /sdcard/"+DateTime.Now.ToString("yyyyMMddHHmmss")+".png"),
        };
        private static AntdUI.BaseCollection _Configs = null;
        public static AntdUI.BaseCollection Configs
        {
            get
            {
                if (_Configs == null)
                {
                    _Configs = new AntdUI.BaseCollection();
                    foreach (var config in OpTypes)
                    {
                        _Configs.Add(config);
                    }
                }
                return _Configs;
            }

        }


        /// <summary>
        /// 模板变量
        /// </summary>
        public class TaskItemDetailTemp
        {
            public string Param;
        }
        public class TaskItem
        {
            /// <summary>
            /// 操作命令 ADB 
            /// </summary>
            public string Oprate;
            /// <summary>
            /// 实际命令 值 例如 100 200 
            /// </summary>
            public string Param;

            /// <summary>
            /// 是否是ADB命令
            /// </summary>
            public bool IsAdb;
            /// <summary>
            /// 操作说明
            /// </summary>
            public string Note;

            /// <summary>
            /// 排序
            /// </summary>
            public int Sort;

        }
        public enum TaskTypeEnum
        {
            /// <summary>
            /// 开始结束时间
            /// </summary>
            datetime = 0,
            /// <summary>
            /// corn表达式
            /// </summary>
            corn = 1
        }

        public enum TaskStateEnum
        {
            /// <summary>
            /// w=未运行
            /// </summary>
            notrun = 0,
            /// <summary>
            /// 运行中
            /// </summary>
            run = 1,
            /// <summary>
            /// 已完成
            /// </summary>
            done = 2
        }
        [Serializable]
        public class TaskInfo
        {
            /// <summary>
            /// 任务名称
            /// </summary>
            public string Name;
            /// <summary>
            /// 任务操作明细
            /// </summary>
            public List<TaskItem> TaskItems;
            public int id;
            /// <summary>
            /// 重复次数
            /// </summary>
            public int RunTimes;
            /// <summary>
            /// 设备名称多个
            /// </summary>
            public string[] DeviceName;
            /// <summary>
            /// corn 表达式
            /// </summary>
            public string Corn;

            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime? StartDeteTime;
            /// <summary>
            /// 结束时间
            /// </summary>
            public DateTime? EndDeteTime;
            /// <summary>
            /// 优先级
            /// </summary>
            public int? Priority;

            /// <summary>
            /// 当前任务状态 0 未开启 1运行中 2 已完成
            /// </summary>
            public TaskStateEnum State;
            /// <summary>
            /// 当前触发器类型 0：开始结束时间 1：corn 表达式
            /// </summary>
            public TaskTypeEnum Type;
            public TaskInfo()
            {
                this.RunTimes = 1;
            }

        }


        public List<TaskInfo> tasks { set; get; }

        private static TaskJson instance = null;

        private static TaskDbContext _db;
        private static readonly object lockObj = new object();
        private TaskJson()
        {

            _db = new TaskDbContext();
        }
        /// <summary>
        /// 单例模式
        /// </summary>
        public static TaskJson Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObj)
                    {
                        if (instance == null)
                        {
                            instance = new TaskJson();
                            instance.tasks = new List<TaskInfo>();
                        }
                    }
                }
                return instance;
            }
        }
        public static TaskInfoTB ConvertToTB(TaskInfo taskInfo)
        {
            return new TaskInfoTB
            {
                id = taskInfo.id,
                Name = taskInfo.Name,
                RunTimes = taskInfo.RunTimes,
                DeviceNames = String.Join(",", taskInfo.DeviceName),
                Corn = taskInfo.Corn,
                StartDeteTime = taskInfo.StartDeteTime,
                EndDeteTime = taskInfo.EndDeteTime,
                Priority = taskInfo.Priority,
                State = taskInfo.State.GetHashCode(),
                Type = taskInfo.Type.GetHashCode(),

            };
        }
        public static TaskItemTB ConvertToItemTB(TaskItem taskItem, int TaskInfoID)
        {
            return new TaskItemTB
            {
                TaskInfoID = TaskInfoID,
                Oprate = taskItem.Oprate,
                Param = taskItem.Param,
                IsAdb = taskItem.IsAdb,
                Note = taskItem.Note,
                Sort = taskItem.Sort
            };
        }

        public static TaskItem ConvertToItem(TaskItemTB taskItemTB)
        {
            return new TaskItem
            {
                Oprate = taskItemTB.Oprate,
                Param = taskItemTB.Param,
                IsAdb = taskItemTB.IsAdb,
                Note = taskItemTB.Note,
                Sort = taskItemTB.Sort
            };
        }

        public static List<TaskItem> GetTaskItems(int TaskInfoID)
        {
            List<TaskItemTB> taskItemTBs = _db.TaskItemTB.Where(p => p.TaskInfoID == TaskInfoID).ToList();

            List<TaskItem> taskItems = new List<TaskItem>();
            foreach (var item in taskItemTBs)
            {
                TaskItem taskitem = ConvertToItem(item);
                taskItems.Add(taskitem);
            }
            return taskItems;
        }

        public static List<TaskInfo> LoadJsonData()
        {
            try
            {
                if (_db == null)
                {
                    _db = new TaskDbContext();
                }
                List<TaskInfoTB> taskInfoTBs = _db.TaskInfoTB.OrderBy(p => p.id).ToList();
                List<TaskInfo> taskInfos = new List<TaskInfo>();
                foreach (var item in taskInfoTBs)
                {

                    TaskInfo taskInfo = new TaskInfo();
                    taskInfo.Name = item.Name;
                    taskInfo.id = item.id;
                    taskInfo.State = (TaskStateEnum)item.State;
                    taskInfo.Corn = item.Corn;
                    taskInfo.Priority = item.Priority;
                    taskInfo.RunTimes = item.RunTimes;
                    taskInfo.StartDeteTime = item.StartDeteTime;
                    taskInfo.EndDeteTime = item.EndDeteTime;
                    taskInfo.Type = (TaskTypeEnum)item.Type;
                    taskInfo.DeviceName = item.DeviceNames.Split(',');
                    taskInfo.TaskItems = GetTaskItems(item.id);
                    taskInfos.Add(taskInfo);
                }
                Instance.tasks = taskInfos;



            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "load json data");
                // 处理异常，例如文件不存在、JSON格式错误等  
                //MessageBox.Show("Error loading JSON data: " + ex.Message);
            }
            return Instance.tasks;
        }
        //public static void SaveJsonData()
        //{
        //    try
        //    {


        //        // 获取程序基目录  
        //        //string basePath = AppDomain.CurrentDomain.BaseDirectory;
        //        //// 构建JSON文件的完整路径  
        //        //string jsonFilePath = Path.Combine(basePath, "task.json"); // 假设你的JSON文件名为data.json  


        //        //try
        //        //{
        //        //    using (FileStream fs = new FileStream(jsonFilePath, FileMode.Open, FileAccess.ReadWrite))
        //        //    {
        //        //        // 在这里进行文件操作
        //        //        SaveJsonData(jsonFilePath);
        //        //    }
        //        //}
        //        //catch (IOException ex)
        //        //{
        //        //    Console.WriteLine("无法访问文件，可能被其他进程占用。错误信息: " + ex.Message);
        //        //}
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelper.Error(ex, "save json data");
        //        // 处理异常，例如文件不存在、JSON格式错误等  
        //        //MessageBox.Show("Error loading JSON data: " + ex.Message);
        //    }
        //}
        //public static void SaveJsonData(string jsonFilePath)
        //{
        //    try
        //    {

        //        if (!File.Exists(jsonFilePath))
        //        {
        //            File.Create(jsonFilePath);
        //        }
        //        string jsonString = JsonConvert.SerializeObject(instance.tasks, Formatting.Indented);
        //        // 将JSON字符串写回到文件  
        //        File.WriteAllText(jsonFilePath, jsonString);
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelper.Error(ex, "save json data");
        //        // 处理异常，例如文件不存在、JSON格式错误等  
        //        //MessageBox.Show("Error loading JSON data: " + ex.Message);
        //    }
        //}

        /// <summary>
        /// 批量增加TaskItem 到数据库
        /// </summary>
        /// <param name="taskItems"></param>
        /// <param name="TaskInfoID"></param>
        /// <returns></returns>
        public static int AddTaskItemTBs(List<TaskItem> taskItems, int TaskInfoID)
        {
            for (int i = 0; i < taskItems.Count; i++)
            {
                TaskItem taskItem = taskItems[i];
                taskItem.Sort = i;
                TaskItemTB itemTB = ConvertToItemTB(taskItem, TaskInfoID);
                _db.TaskItemTB.Add(itemTB);
            }

            return _db.SaveChanges();
        }
        public static void AddMultiTask(List<TaskInfo> taskinfos)
        {
            try
            {
                //List<TaskInfoTB> taskInfoTBs = new List<TaskInfoTB>();
                //List<TaskItemTB> taskItemTBs = new List<TaskItemTB>();
                _db.Configuration.AutoDetectChangesEnabled = false;// 解决批量性能问题
                _db.Configuration.ValidateOnSaveEnabled = false;// 解决“对一个或多个实体的验证失败。”

                foreach (var item in taskinfos)
                {
                    TaskInfo task = AddTaskItem(item);

                    TaskInfoTB taskinfotb_item = _db.TaskInfoTB.Where(p => p.id == task.id).FirstOrDefault();
                    if (taskinfotb_item != null)
                    {
                        taskinfotb_item.Name = task.Name;

                    }
                    else
                    {
                        TaskInfoTB infoTB = ConvertToTB(task);
                        _db.Entry(infoTB).State = System.Data.Entity.EntityState.Added;
                        _db.TaskInfoTB.Add(infoTB);
                        //taskInfoTBs.Add(infoTB);

                        for (int i = 0; i < task.TaskItems.Count; i++)
                        {
                            TaskItem taskItem = task.TaskItems[i];
                            taskItem.Sort = i;
                            TaskItemTB itemTB = ConvertToItemTB(taskItem, task.id);
                            _db.TaskItemTB.Add(itemTB);
                            //taskItemTBs.Add(itemTB);
                        }




                    }

                }

                _db.SaveChanges();
                
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                _db.Configuration.AutoDetectChangesEnabled = true;// 解决批量性能问题
                _db.Configuration.ValidateOnSaveEnabled = true;// 解决“对一个或多个实体的验证失败。”
            }
           
        }
        public static void AddTask(TaskInfo task)
        {
            try
            {
                task.id = 1;
                if (instance == null) return;

                if (instance.tasks.Count != 0)
                {
                    task.id = Instance.tasks.Max(n => n.id) + 1;
                }

                instance.tasks.Add(task);

                TaskInfoTB item = _db.TaskInfoTB.Where(p => p.id == task.id).FirstOrDefault();
                if (item != null)
                {
                    item.Name = task.Name;

                }
                else
                {
                    TaskInfoTB infoTB = ConvertToTB(task);
                    _db.TaskInfoTB.Add(infoTB);

                    for (int i = 0; i < task.TaskItems.Count; i++)
                    {
                        TaskItem taskItem = task.TaskItems[i];
                        taskItem.Sort = i;
                        TaskItemTB itemTB = ConvertToItemTB(taskItem, task.id);
                        _db.TaskItemTB.Add(itemTB);
                    }

                    _db.SaveChanges();


                }
            }
            catch (Exception ex)
            {
                // 处理异常或记录日志
                Tools.LogHelper.Error(ex.Message);
                throw;
            }


            //SaveJsonData();
        }
        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="id"></param>
        public static void DelTask(int id)
        {
            instance.tasks.Remove(Instance.tasks.Where(n => n.id == id).First());
            TaskInfoTB infoTB = _db.TaskInfoTB.Where(p => p.id == id).FirstOrDefault();
            if (infoTB != null)
            {
                _db.TaskInfoTB.Attach(infoTB);
                _db.TaskInfoTB.Remove(infoTB);
            }


            List<TaskItemTB> taskItemTBs = _db.TaskItemTB.Where(p => p.TaskInfoID == id).ToList();
            DeleteTaskItems(taskItemTBs);
            _db.SaveChanges();
            //SaveJsonData();
        }
        /// <summary>
        /// 清空
        /// </summary>
        public static int ClearTask()
        {  // 记录任务开始时间
            DateTime start = DateTime.Now;

            int resint = 0;
            try
            {
                _db.Configuration.AutoDetectChangesEnabled = false;// 解决批量性能问题
                _db.Configuration.ValidateOnSaveEnabled = false;// 解决“对一个或多个实体的验证失败。”
               
                if (instance != null && instance.tasks.Count > 0)
                    instance.tasks.Clear(); // 清空列表;
                List<TaskInfoTB> infoTBs = _db.TaskInfoTB.ToList();
                if (infoTBs.Count > 0)
                {
                    //string clear_TaskInfoTB_sql = " DELETE FROM  TaskInfoTB;";

                    //resint = _db.Database.ExecuteSqlCommand(clear_TaskInfoTB_sql);

                    //string clear_TaskItemTB_sql = "  DELETE FROM  TaskItemTB;";

                    //_db.Database.ExecuteSqlCommand(clear_TaskItemTB_sql);

                    //string clear_TaskInfoTB_sequence_sql = "DELETE FROM sqlite_sequence WHERE name = 'TaskInfoTB';";

                    //resint = _db.Database.ExecuteSqlCommand(clear_TaskInfoTB_sequence_sql);

                    //string clear_TaskItemTB_sequence_sql = "DELETE FROM sqlite_sequence WHERE name = 'TaskItemTB';";

                    //_db.Database.ExecuteSqlCommand(clear_TaskItemTB_sequence_sql);
                    foreach (var infoTB in infoTBs)
                    {
                        if (infoTB != null)
                        {
                            _db.TaskInfoTB.Attach(infoTB);
                            Console.WriteLine($"TaskInfoTB {infoTB.Name}");
                        }

                    }
                    _db.TaskInfoTB.RemoveRange(infoTBs);

                    List<TaskItemTB> taskItemTBs = _db.TaskItemTB.ToList();
                    foreach (var item in taskItemTBs)
                    {
                        if (item != null)
                        {
                            _db.TaskItemTB.Attach(item);
                            Console.WriteLine($"TaskItemTB {item.TaskInfoID}");
                        }

                    }
                    _db.TaskItemTB.RemoveRange(taskItemTBs);

                    resint = _db.SaveChanges();
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                _db.Configuration.AutoDetectChangesEnabled = true;// 解决批量性能问题
                _db.Configuration.ValidateOnSaveEnabled = true;// 解决“对一个或多个实体的验证失败。”
            }

            // 记录任务结束时间
            DateTime end = DateTime.Now;

            // 计算时间差
            TimeSpan duration = end - start;

            Console.WriteLine($"任务执行时间: {duration.TotalSeconds} 秒");
            return resint;

        }
        public static void DeleteTaskInfos(List<TaskInfoTB> infoTBs)
        {
            foreach (var infoTB in infoTBs)
            {
                if (infoTB != null)
                {
                    _db.TaskInfoTB.Attach(infoTB);
                    _db.TaskInfoTB.Remove(infoTB);
                }

            }

            _db.SaveChanges();
        }
        /// <summary>
        /// 删除指定TaskItem集合
        /// </summary>
        /// <param name="taskItemTBs"></param>
        public static void DeleteTaskItems(List<TaskItemTB> taskItemTBs)
        {
            foreach (var item in taskItemTBs)
            {
                if (item != null)
                {
                    _db.TaskItemTB.Attach(item);
                    _db.TaskItemTB.Remove(item);
                }

            }
            _db.SaveChanges();
        }
        public static void EditTask(TaskInfo task)
        {
            var t = Instance.tasks.Where(n => n.id == task.id).First();
            t.TaskItems = task.TaskItems;
            t.Name = task.Name;
            t.DeviceName = task.DeviceName;
            //SaveJsonData();

            TaskInfoTB item = _db.TaskInfoTB.Where(p => p.id == task.id).FirstOrDefault();
            if (item != null)
            {
                item.Name = task.Name;
                if (task.DeviceName.Length > 0)
                    item.DeviceNames = String.Join(",", task.DeviceName);
                else
                    item.DeviceNames = null;

                //先删除旧的再插入新的
                List<TaskItemTB> taskItemTBs = _db.TaskItemTB.Where(p => p.TaskInfoID == item.id).ToList();
                DeleteTaskItems(taskItemTBs);


                AddTaskItemTBs(task.TaskItems, task.id);

                item.Corn = task.Corn;
                item.StartDeteTime = task.StartDeteTime;
                item.EndDeteTime = task.EndDeteTime;
                item.RunTimes = task.RunTimes;
                item.Type = task.Type.GetHashCode();
                item.Priority = task.Priority;

            }
            _db.SaveChanges();


        }

        /// <summary>
        /// 获取最晚的DateTime
        /// </summary>
        /// <param name="tasks"></param>
        /// <returns></returns>
        public static DateTime? GetLatestEndDateTime(List<TaskInfo> tasks)
        {
            DateTime? latest = null;
            foreach (var task in tasks)
            {
                if (task.EndDeteTime.HasValue && (latest == null || task.EndDeteTime > latest))
                {
                    latest = task.EndDeteTime;
                }
            }
            return latest;
        }

        public static void TaskRandom(DateTime start, DateTime end, List<ScheduleDevice> newDevices, List<TaskJson.TaskItem> list, Random random, List<ReferenceSource> referenceSource, int deviceWorkTimeInSeconds = 90)
        {


            TimeSpan totalScheduleTime = end - start;// 12:00 to 15:00

            //已存在的设备任务
            List<ScheduleDevice> assignedDevices = new List<ScheduleDevice>();

            if (instance.tasks.Count > 0)
            {
                for (int i = 0; i < instance.tasks.Count; i++)
                {
                    TaskInfo ti = instance.tasks[i];

                    if (ti != null)
                    {
                        if (ti.DeviceName != null)
                        {
                            if (ti.DeviceName.Length > 0 && string.IsNullOrEmpty(ti.Corn))
                            {
                                foreach (var item in ti.DeviceName)
                                {
                                    ScheduleDevice d = new ScheduleDevice();
                                    d.Name = item;
                                    d.WorkContent = ti.Name;
                                    if (ti.StartDeteTime != null)
                                        d.StartTime = (DateTime)ti.StartDeteTime;
                                    if (ti.EndDeteTime != null)
                                        d.EndTime = (DateTime)ti.EndDeteTime;
                                    assignedDevices.Add(d);


                                }
                            }
                        }
                        else if (!string.IsNullOrEmpty(ti.Corn))
                        {
                            DelTask(ti.id);
                        }
                    }

                }
            }

            // 定义固定的时间区间段
            DateTime startOfInterval = start;
            DateTime endOfInterval = end;
            //int deviceWorkTimeInSeconds = 30;  // 新增设备工作时间参数

            List<ScheduleDevice> assignedNewDevices = Schedule.AssignNewDevicesRandomlyWithinInterval(assignedDevices, newDevices, startOfInterval, endOfInterval, random, deviceWorkTimeInSeconds);
            Random randomTemp = new Random();
            Console.WriteLine("最终的设备调度时间安排：");
            int taskIndex = 0;
            foreach (var device in assignedNewDevices)
            {
                Console.WriteLine($"{device.Name}: {device.StartTime} - {device.EndTime}");
                // 生成一个 0 到 100 之间的随机整数
                int randomNumber = randomTemp.Next(0, 10000);
                TaskInfo ti = new TaskInfo();
                ti.Type = 0;// 时间
                ti.Name = "自动排班" + randomNumber.ToString() + ":" + device.Name;
                ti.DeviceName = new string[] { device.Name };
                ti.StartDeteTime = device.StartTime;
                ti.EndDeteTime = device.EndTime;
                List<TaskItem> temp = new List<TaskItem>();
                temp = FilterTaskItem(list, referenceSource, taskIndex);
                string tempstr = JsonConvert.SerializeObject(temp);
                ti.TaskItems = JsonConvert.DeserializeObject<List<TaskItem>>(tempstr);
                taskIndex++; // 移动到下一个task

                if (referenceSource != null)
                {
                    // 当taskIndex等于tasks.Length时，重置它，模拟从头再次分配的效果（虽然实际上不需要，因为%已经处理了）
                    if (taskIndex == referenceSource.Count)
                    {
                        taskIndex = 0; // 实际上，由于%运算，这一行是多余的，但为了直观性保留
                    }
                }

                ti.Priority = 1;

                AddTaskItem(ti);
            }
            List<TaskInfoTB> taskInfoTBs = new List<TaskInfoTB>();
            List<TaskItemTB> taskItemTBs = new List<TaskItemTB>();
            foreach (TaskInfo task in instance.tasks)
            {
                TaskInfoTB item = _db.TaskInfoTB.Where(p => p.id == task.id).FirstOrDefault();
                if (item != null)
                {
                    item.Name = task.Name;

                }
                else
                {
                    TaskInfoTB infoTB = ConvertToTB(task);
                    taskInfoTBs.Add(infoTB);

                    for (int i = 0; i < task.TaskItems.Count; i++)
                    {
                        TaskItem taskItem = task.TaskItems[i];
                        taskItem.Sort = i;
                        TaskItemTB itemTB = ConvertToItemTB(taskItem, task.id);
                        taskItemTBs.Add(itemTB);
                    }

                }
            }

            _db.TaskInfoTB.AddRange(taskInfoTBs);
            _db.TaskItemTB.AddRange(taskItemTBs);
            _db.SaveChanges();
        }
        /// <summary>
        /// 处理操作步骤，默认处理 Note=referenceSource 的外部数据源
        /// </summary>
        /// <param name="taskItems"></param>
        /// <param name="referenceSource"></param>
        /// <returns></returns>
        private static List<TaskItem> FilterTaskItem(List<TaskItem> taskItems, List<ReferenceSource> referenceSource, int taskIndex)
        {
            List<TaskItem> resultTaskItem = new List<TaskItem>();
            for (int i = 0; i < taskItems.Count; i++)
            {
                TaskItem taskItem = taskItems[i];
                if (taskItem != null)
                {
                    if (taskItem.Note == "referenceSource")
                    {
                        if (referenceSource != null)
                        {

                            ReferenceSource randomElement = referenceSource[taskIndex % referenceSource.Count]; // 使用取模确保索引不越界
                            taskItem.Param = randomElement.RContent;
                            Console.WriteLine($"顺序获取的对象是: {randomElement.RContent}");
                            //// 在这里执行随机选择操作
                            //Random rnd = new Random();
                            //int index = rnd.Next(referenceSource.Count);
                            //ReferenceSource randomElement = referenceSource[index];
                            //taskItem.Param = randomElement.RContent;
                            //// 输出结果
                            //Console.WriteLine($"随机获取的对象是: {randomElement.RContent}");
                            //////// 使用 RandomNumberGenerator 生成一个随机索引
                            //byte[] randomBytes = new byte[4]; // 假设我们使用一个 32 位的随机数
                            //using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
                            //{
                            //    rng.GetBytes(randomBytes);
                            //    // 注意：这里我们简单地将字节数组转换为 int，但实际上需要更复杂的处理来确保索引在有效范围内
                            //    // 这里只是为了演示，因此假设数组长度不会超过 int.MaxValue，并且随机生成的数会被模运算限制在数组长度内
                            //    int index = BitConverter.ToInt32(randomBytes, 0) % referenceSource.Count;
                            //    // 确保索引是非负的（虽然在这个例子中由于模运算结果总是非负的，这一步是多余的）
                            //    index = index < 0 ? index + referenceSource.Count : index;

                            //    // 使用随机索引从数组中获取对象

                            //    ReferenceSource randomElement = referenceSource[index];
                            //    taskItem.Param = randomElement.RContent;
                            //    // 输出结果
                            //    Console.WriteLine($"随机获取的对象是: {randomElement.RContent}");
                            //}
                        }
                        else
                        {

                            taskItem.Param = " 😀";
                        }
                    }

                    resultTaskItem.Add(taskItem);
                }
            }
            return resultTaskItem;
        }
        public static TaskInfo AddTaskItem(TaskInfo task)
        {
            try
            {
                task.id = 1;
                if (instance == null) return task;

                if (instance.tasks.Count != 0)
                {
                    task.id = Instance.tasks.Max(n => n.id) + 1;
                }

                instance.tasks.Add(task);


                return task;
            }
            catch (Exception ex)
            {
                // 处理异常或记录日志
                Tools.LogHelper.Error(ex.Message);
                throw;
            }


            //SaveJsonData();
        }

    }



}


